package stack;

/**
 * Created by Administrator on 2017/10/9/009.
 */
public class LinkedStack<T> implements Stack<T> {
    private int count;
    private LinearNode<T> top;
    public LinkedStack()
    {
        count = 0;
        top = null;
    }
    public T pop() throws Exception
    {
        if (count==0)
            throw new Exception("PopException");
        T result = top.getElement();
        top = top.getNext();
        count--;
        return result;
    }
    public String toString()
    {
        String result = "<top of stack>\n";
        LinearNode current = top;
        while (current != null)
        {
            result += (current.getElement()).toString() + "\n";
            current = current.getNext();
        }

        return result + "<bottom of stack>";
    }
    public void push (T element)
    {
        LinearNode<T> node = new LinearNode<T> (element);
        node.setNext(top);
        top = node;
        count++;
    }

    public T peek() throws Exception
    {
        if (count==0)
            throw new Exception("PeepException");
        return top.getElement();
    }
    public boolean isEmpty()
    {
        return (count == 0);
    }
    public int size()
    {
        return count;
    }
}
